<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="改变积分数量" prop="changeCount">
        <el-input
          v-model="queryParams.changeCount"
          placeholder="请输入改变积分数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="店铺ID" prop="shopId">
        <el-input
          v-model="queryParams.shopId"
          placeholder="请输入店铺ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="积分数量" prop="integralNumber">
        <el-input
          v-model="queryParams.integralNumber"
          placeholder="请输入积分数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shop:integral:add']"
          >新增</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:integral:edit']"
          >修改</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:integral:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shop:integral:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="integralList"
      empty-text="积分为空"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="积分编号" align="center" prop="integralId" />
      <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
      <el-table-column
        label="积分改变的类型"
        align="center"
        prop="changeType"
      />
      <el-table-column label="改变积分数量" align="center" prop="changeCount" />
      <el-table-column label="店铺编号" align="center" prop="shopId" />
      <el-table-column label="积分数量" align="center" prop="integralNumber" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleExchange(scope.row)"
            v-hasPermi="['shop:integral:edit']"
            >去使用</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:integral:remove']"
            >清空</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 展示用户使用该店铺积分可兑换的优惠券 -->
    <el-dialog :title="title" v-model="open" width="1100px" append-to-body>
      <!-- 添加空数据提示 -->
      <el-empty
        v-if="!couponList.length"
        description="当前积分不足以兑换任何优惠券"
      />
      <el-table
      v-else
        v-loading="loading"
        :data="couponList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="优惠券ID" align="center" prop="couponId" />
        <el-table-column label="优惠金额" align="center" prop="couponPrice" />
        <el-table-column
          label="优惠券起始日期"
          align="center"
          prop="couponTimeStart"
          width="180"
        >
          <template #default="scope">
            <span>{{
              parseTime(scope.row.couponTimeStart, "{y}-{m}-{d}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="优惠券类型" align="center" prop="couponType" />
        <el-table-column
          label="优惠券折扣率"
          align="center"
          prop="couponDiscount"
        />
        <el-table-column
          label="最低消费多少金额可用优惠券"
          align="center"
          prop="couponMin"
        />
        <el-table-column
          label="优惠券截止日期"
          align="center"
          prop="couponTimeEnd"
          width="180"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.couponTimeEnd, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="积分换购" align="center" prop="couponTrade" />
        <el-table-column label="优惠券图片" align="center" prop="couponPic">
          <template #default="scope">
            <img
              v-if="scope.row.couponPic"
              :src="scope.row.couponPic"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="店铺" align="center" prop="shopName" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm()">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Integral">
import {
  listIntegral,
  getIntegral,
  delIntegral,
  addIntegral,
  updateIntegral,
  exchangeCoupon,
} from "@/api/shop/integral";
import { getCanExchangeCoupon } from "@/api/shop/coupon";
import { getCurrentInstance, ref, reactive, watch, toRefs } from "vue";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const integralList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  couponList: [],
  couponIds: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    changeType: null,
    changeCount: null,
    shopId: null,
    integralNumber: null,
  },
  queryCouponParams: {
    pageNum: 1,
    pageSize: 10,
    couponPrice: null,
    couponTimeStart: null,
    couponType: null,
    couponDiscount: null,
    couponMin: null,
    couponTimeEnd: null,
    couponTrade: null,
    couponPic: null,
    shopId: null,
  },
  rules: {},
});

const { queryParams, queryCouponParams, form, couponList, couponIds, rules } =
  toRefs(data);

/** 查询积分列表 */
function getList() {
  loading.value = true;
  queryParams.value.userId = userStore.id;
  listIntegral(queryParams.value).then((response) => {
    integralList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    integralId: null,
    userId: null,
    changeType: null,
    changeCount: null,
    shopId: null,
    integralNumber: null,
  };
  proxy.resetForm("integralRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 用户在某店铺积分数量
const integralNum = ref();
// 优惠券兑换所需积分数量
const couponNeedIntegral = ref();
// 多选框选中数据
function handleSelectionChange(selection) {
  // ids.value = selection.map(item => item.integralId);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
  selection.forEach((element) => {
    couponNeedIntegral.value = element.couponTrade;
    if (couponNeedIntegral.value > integralNum.value) {
      ElMessage.error("积分不足");
    } else {
      couponIds.value.push(element.couponId);
      console.log(couponIds.value);
    }
  });
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加积分";
}

/** 使用积分按钮操作 */
function handleExchange(row) {
  reset();
  integralNum.value = row.integralNumber;
  // const _integralId = row.integralId || ids.value
  queryCouponParams.value.shopId = row.shopId;
  queryCouponParams.value.couponTrade = row.integralNumber;
  getCanExchangeCoupon(queryCouponParams.value).then((response) => {
    couponList.value = response.rows;
    open.value = true;
    title.value = "优惠券兑换";
  });
}

/** 兑换优惠券提交按钮 */
function submitForm() {
  if (couponNeedIntegral.value > integralNum.value) {
    ElMessage.error("积分不足");
  } else {
    exchangeCoupon(
      userStore.id,
      queryCouponParams.value.shopId,
      couponIds.value,
      couponNeedIntegral.value,
      integralNum.value
    )
      .then((response) => {
        proxy.$modal.msgSuccess("兑换成功");
        open.value = false;
        getList();
        couponIds.value = []; // 重置优惠券ID数组
      })
      .catch((error) => {
        getList();
        console.log(error);
      });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _integralIds = row.integralId || ids.value;
  proxy.$modal
    .confirm('是否确认删除积分编号为"' + _integralIds + '"的数据项？')
    .then(function () {
      return delIntegral(_integralIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "shop/integral/export",
    {
      ...queryParams.value,
    },
    `integral_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
